#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <stdio.h>

#define LOG_TAMANHO_MAX 2048

void glslVerificaErros(unsigned int shader_index)
{
	int params = -1;
	glGetShaderiv(shader_index, GL_COMPILE_STATUS, &params);
	if (GL_TRUE != params) {
		//fprintf (stderr, "\nERROR: GL shader index %i did not compile\n", shader_index);
		char log[LOG_TAMANHO_MAX];
		glGetShaderInfoLog (shader_index, LOG_TAMANHO_MAX, NULL, log);
		printf ("GLSL_ERROR: GL Shader index %i:\n%s\n", shader_index, log);
	}
	else
		printf("GLSL: Compilação bem sucedida.\n");
}



const char* LeArquivo(FILE* pfile, long int* psize)
{
	int i;
	fseek(pfile, 0, SEEK_END);
	long int size = ftell(pfile);
	fseek(pfile, 0, SEEK_SET);

	char* conteudo = (char*) malloc(size+1);
	for(i=0;i<size;i++)
		conteudo[i] = fgetc(pfile);
	conteudo[i] = '\0';
	
	psize = &size;
	
	return conteudo;
}



unsigned int glslCompile(FILE* vs_file, FILE* fs_file)
{
	long int *pfilesize;

	const char* vertex_shader = LeArquivo(vs_file, pfilesize);
	const GLint vs_filesize = (const GLint) *pfilesize;

	unsigned int vs = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vs, 1, &vertex_shader, NULL);

	printf("GLSL: Compilando vertex shader...\n");
	glCompileShader(vs);	
	glslVerificaErros(vs);

	const char* fragment_shader = LeArquivo(fs_file, pfilesize);
	const GLint fs_filesize = (const GLint) *pfilesize;

	unsigned int fs = glCreateShader (GL_FRAGMENT_SHADER);
	glShaderSource(fs, 1, &fragment_shader, NULL);

	printf("GLSL: Compilando fragment shader...\n");
	glCompileShader(fs);	
	glslVerificaErros(fs);

	unsigned int shader_programme = glCreateProgram();
	glAttachShader(shader_programme, fs);
	glAttachShader(shader_programme, vs);
	glLinkProgram(shader_programme);

	return shader_programme;
}